package cn.buildoncloud.labor.workermanapplet.sys.modules.services.impl;

import cn.buildoncloud.labor.workermanapplet.dto.AppletUserDTO;
import cn.buildoncloud.labor.workermanapplet.dto.SysUserDTO;
import cn.buildoncloud.labor.workermanapplet.sys.modules.services.AuthorityService;
import cn.buildoncloud.labor.workermanapplet.util.AppletUtil;
import com.alibaba.fastjson.JSONObject;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.Record;
import org.nutz.dao.sql.Sql;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: cn.buildoncloud.labor.workermanapplet.sys.modules.services.impl
 * Created by CuiZibo on 2018/11/21 16:37
 */
@Service
public class AuthorityServiceImpl implements AuthorityService {

    private static final Logger log = LoggerFactory.getLogger(AuthorityServiceImpl.class);

    public AuthorityServiceImpl(Dao dao) {
        this.dao = dao;
    }

    private Dao dao;

    @Value("${webSystemIP}")
    private String webSystemIP;

    /**
     * 通过code获取openid 如果信息存在则查询对应的用户信息返回 如果不存在则返回一个标记 跳转到绑定页面绑定
     * @param code
     * @return
     */
    @Override
    public Map<String, Object> getOpenIdAndCheckExists(String code) {

        Map<String, Object> data = new HashMap<>();
        boolean flag = false;
        JSONObject sessionKeyAndOpenid = AppletUtil.getSessionKeyAndOpenid(code);
        String openId = sessionKeyAndOpenid.getString("openid");
        if (openId == null) {
            return null;
        }
        SysUserDTO sysUserDTO = queryBindSysUserInfo(openId);
        if (sysUserDTO != null && sysUserDTO.getId() != null) {
            log.info("SysUserDTO sysUserDTO"+sysUserDTO.getId());
            flag = true;
            data.put("sysUserDTO", sysUserDTO);
        }
        data.put("openId", openId);
        data.put("flag", flag);
        log.info("Map<String, Object>"+data);
        return data;
    }

    /**
     * 绑定操作 appletUser 和 sysUser 绑定
     * @param openId
     * @param userId
     * @return
     */
    @Override
    public int bind(String openId, String userId) {
        Record record = dao.fetch("applet_user", Cnd.where("openid", "=", openId));
        if (record == null) return 0;
        int count = dao.count("applet_user_sys_user", Cnd.where("applet_user_id", "=", record.get("id")).and("sys_user_id", "=", userId).and("state", "=", 0));
        if (count != 0) return 0;
        Sql sql = Sqls.create("INSERT INTO `applet_user_sys_user` (`applet_user_id`, `sys_user_id`, `state`) VALUES ((SELECT id FROM applet_user where openid = @openId), @sysUserId, 0)");
        sql.setParam("sysUserId", userId).setParam("openId", openId);
        dao.execute(sql);
        int i = sql.getUpdateCount();
        return i;
    }

    /**
     * 通过手机号查询用户信息
     * @param phoneNumber
     * @return
     */
    @Override
    public SysUserDTO querySysUserByPhone(String phoneNumber) {
        Sql sql = Sqls.create("SELECT CONCAT(t.id,'') id, t.loginname, t.username, t.phone, t.email, CONCAT(t.unitid,'') unitid, CONCAT(t.images_id,'') images_id FROM `sys_user` t WHERE t.phone = @phone AND t.approvalState = 0 AND t.disabled = 0");
        sql.setParam("phone", phoneNumber)
                .setCallback((conn, rs, sql1) -> {
                    List<SysUserDTO> list = new ArrayList<>();
                    while (rs.next()) {
                        SysUserDTO sysUserDTO = new SysUserDTO();
                        sysUserDTO.setId(rs.getString("id"));
                        sysUserDTO.setLoginname(rs.getString("loginname"));
                        sysUserDTO.setUsername(rs.getString("username"));
                        sysUserDTO.setPhone(rs.getString("phone"));
                        sysUserDTO.setUnitid(rs.getString("unitid"));
                        sysUserDTO.setEmail(rs.getString("email"));
                        sysUserDTO.setImagesId(rs.getString("images_id"));
                        list.add(sysUserDTO);
                    }
                    return list;
                });
        dao.execute(sql);
        List<SysUserDTO> list = sql.getList(SysUserDTO.class);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 通过openId查询小程序用户
     * @param openId
     * @return
     */
    @Override
    public AppletUserDTO queryAppletByOpenId(String openId) {

        Sql sql = Sqls.create("SELECT * FROM applet_user t1 WHERE t1.openid = @openId");
        sql.setParam("openId", openId)
                .setCallback((conn, rs, sql1) -> {
                    List<AppletUserDTO> list = new ArrayList<>();
                    while (rs.next()) {
                        AppletUserDTO appletUserDTO = new AppletUserDTO();
                        appletUserDTO.setId(rs.getString("id"));
                        appletUserDTO.setOpenId(rs.getString("openid"));
                        appletUserDTO.setNickName(rs.getString("nick_name"));
                        appletUserDTO.setGender(rs.getString("gender"));
                        appletUserDTO.setCity(rs.getString("city"));
                        appletUserDTO.setProvince(rs.getString("province"));
                        appletUserDTO.setCountry(rs.getString("country"));
                        appletUserDTO.setAvatarUrl(rs.getString("avatar_url"));
                        appletUserDTO.setUnionId(rs.getString("union_id"));
                        list.add(appletUserDTO);
                    }
                    return list;
                });
        dao.execute(sql);
        List<AppletUserDTO> list = sql.getList(AppletUserDTO.class);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public int unBind(String userId, String appletUserId) {

        int update = dao.update("applet_user_sys_user", Chain.make("state", 1), Cnd.where("applet_user_id", "=", appletUserId).and("sys_user_id", "=", userId).and("state", "=", 0));
        return update;
    }

    /**
     * 查询用户是否绑定
     * @param userId
     * @param appletUserId
     * @return
     */
    @Override
    public boolean queryIsBind(String userId, String appletUserId) {
        int count = dao.count("applet_user_sys_user", Cnd.where("sys_user_id", "=", userId).and("applet_user_id", "=", appletUserId).and("state", "=", 0));
        if (count == 1) {
            return true;
        }
        return false;

    }

    //通过openId查询绑定的用户信息
    private SysUserDTO queryBindSysUserInfo(String openId) {
        Sql sql = Sqls.create("SELECT CONCAT(t3.id,'') id, t3.loginname, t3.username, t3.phone, t3.email, CONCAT(t3.unitid,'') unitid, CONCAT(t3.images_id,'') images_id FROM `applet_user` t1 LEFT JOIN applet_user_sys_user t2 ON t2.applet_user_id = t1.id AND t2.state = 0 LEFT JOIN sys_user t3 ON t3.id = t2.sys_user_id AND t3.disabled = 0 AND t3.approvalState = 0 WHERE t1.openid = @openId");
        sql.setParam("openId", openId)
                .setCallback((conn, rs, sql1) -> {
                    List<SysUserDTO> list = new ArrayList<>();
                    while (rs.next()) {
                        SysUserDTO sysUserDTO = new SysUserDTO();
                        sysUserDTO.setId(rs.getString("id"));
                        sysUserDTO.setLoginname(rs.getString("loginname"));
                        sysUserDTO.setUsername(rs.getString("username"));
                        sysUserDTO.setPhone(rs.getString("phone"));
                        sysUserDTO.setUnitid(rs.getString("unitid"));
                        sysUserDTO.setEmail(rs.getString("email"));
                        sysUserDTO.setImagesId(rs.getString("images_id"));
                        list.add(sysUserDTO);
                    }
                    return list;
                });
        dao.execute(sql);
        List<SysUserDTO> list = sql.getList(SysUserDTO.class);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

}
